package com.example.environmentset.listener;

import com.example.environmentset.service.PortSetService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 获取web应用启动时的端口
 *
 * @author fangyuan.xia
 * @since 2022-08-13
 */
@Component
@Slf4j
public class WebEnvironmentSetListener implements ApplicationListener<WebServerInitializedEvent> {

    @SneakyThrows
    @Override
    public void onApplicationEvent(WebServerInitializedEvent serverInitializedEvent) {
        if (!(serverInitializedEvent instanceof ServletWebServerInitializedEvent)) {
            log.warn("Not support for non servlet project");
            return;
        }
        String context = serverInitializedEvent.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path");
        if (!StringUtils.hasText(context)) {
            log.error("There is not context path!!!");
            throw new RuntimeException("There is not context path!!!");
        }
        context = context.replaceAll("/", "");
        int port = serverInitializedEvent.getWebServer().getPort();
        log.info("{} webPortSet port={}", context, port);

        //
        PortSetService portSetService = serverInitializedEvent.getApplicationContext().getBean(PortSetService.class);
        portSetService.set(context, port);

    }


}
